package cn.com.taiji.oospub.wechat.controller.course;


import cn.com.taiji.model.finals.SessionNames;
import cn.com.taiji.oospub.wechat.common.Finals;
import cn.com.taiji.oospub.wechat.common.tool.DoubleTools;
import cn.com.taiji.oospub.wechat.entity.*;
import cn.com.taiji.oospub.wechat.service.*;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品表 前端控制器
 * </p>
 *
 * @author
 * @since 2020-10-30
 */
@Controller
@RequestMapping("/wx/courses")
@Slf4j
public class CoursesController {
    @Value("${PROPASS}")
    public String PROPASS;
    @Value("${PROJECT_CODE}")
    public String PROJECT_CODE;
    @Value("${CUS_NAME}")
    public String CUS_NAME;

    @Autowired
    private ICoursesService coursesService;
    @Autowired
    private ICourseTypeService coursesTypeService;
    @Autowired
    private IMemberBaseInfoService memberBaseInfoService;
    @Autowired
    private IRecipeMaterialNumService recipeMaterialNumService;
    @Autowired
    private IMealTimeService mealTimeService;
    @Autowired
    private ICoursesOrdersDetailsService coursesOrdersDetailsService;
    @Autowired
    private ICourseNutritionService coursesNutritionService;
    @Autowired
    private ICoursesImgService coursesImgService;
    @Autowired
    private ISchoolBaseInfoService schoolBaseInfoService;
    @Autowired
    private IRestaurantService restaurantService;
    @Autowired
    private ISchoolImgService schoolImgService;
    @Autowired
    private ICourseNotesService courseNotesService;
    @Autowired
    private IAccesstokensaveService accesstokensaveService;
    @Autowired
    private INoticeMainInfoService noticeMainInfoService;


    /**
     * 主页轮播图(新闻主题)
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/systemNoticeList", method = RequestMethod.GET)
    @ResponseBody
    public String systemNoticeList(Model model, HttpServletRequest request) {
        MemberBaseInfo loginUser = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        QueryWrapper<NoticeMainInfo> noticeMainInfoWrapper = new QueryWrapper<>();
        noticeMainInfoWrapper.eq("status", "open");
//        noticeMainInfoWrapper.ge("create_time", LocalDate.now().minusMonths(1));
//        noticeMainInfoWrapper.le("create_time", LocalDateTime.now());
        noticeMainInfoWrapper.orderByDesc("create_time");
        List<JSONObject> systemNoticeList = JSONObject.parseArray(JSONObject.toJSONString(noticeMainInfoService.list(noticeMainInfoWrapper)), JSONObject.class);
        List<JSONObject> schoolImgsList = JSONObject.parseArray(JSONObject.toJSONString(schoolImgService.findBySchoolId(loginUser.getSchoolId())), JSONObject.class);
        systemNoticeList.addAll(schoolImgsList);
        return JSONObject.toJSONString(systemNoticeList);
    }


    /**
     * 预约点餐查询菜品
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/manage", method = RequestMethod.POST)
    @ResponseBody
    public String getDayMenuWithType(Model model, HttpServletRequest request, HttpServletResponse response) {

        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        SchoolBaseInfo schoolBaseInfo = schoolBaseInfoService.getById(member.getSchoolId());
//        String restaurantId = member.getRestaurant().getId();
        String restaurantId = "";
        String mealTimeCode = request.getParameter("mealTimeCode");
        String dateNum = request.getParameter("dateNum");
        String schoolId = member.getSchoolId();
        List<Courses> list = new ArrayList<>();
        //查询菜品分类
        List<CourseType> courseTypes = coursesTypeService.coursesTypelist(member);
        //查询全部菜品
        list = coursesService.listdayMenu(mealTimeCode, schoolId, dateNum, "dc", restaurantId);
        LocalTime nowTime = LocalTime.now();

        List<CoursesImg> coursesImgList = new ArrayList<>();
        //查询菜品主图
        for (Courses cc : list) {
            //--------查询菜品主图开始----------
            coursesImgList = coursesImgService.query()
                    .eq("course_pos_no", cc.getPosNo())
                    .isNotNull("img_path")
                    .isNotNull("img_url")
                    .orderByDesc("mainImg").list();
            if (coursesImgList != null && coursesImgList.size() > 0) {
                cc.setImageMainPath(coursesImgList.get(0).getImgUrl());
            }
            //--------查询菜品主图结束----------
            //查询营养标签
            if (null != cc.getCnList() && cc.getCnList().size() > 0) {
                for (CourseNutrition courseNutrition : cc.getCnList()) {
                    //营养标签
                    if ("dz.png".equals(courseNutrition.getTagLogo())) {
                        cc.setDzLogo("dz.png");
                    } else if ("dk.png".equals(courseNutrition.getTagLogo())) {
                        cc.setDkLogo("dk.png");
                    } else if ("dy.png".equals(courseNutrition.getTagLogo())) {
                        cc.setDyLogo("dy.png");
                    } else if ("gw.png".equals(courseNutrition.getTagLogo())) {
                        cc.setGwLogo("gw.png");
                    }
                }
            }
        }
        //筛选推荐菜品
        model.addAttribute("tuijianList", list.stream().filter(i -> "1".equals(i.getIsTop())).collect(Collectors.toList()));

        //周一时间
        LocalDate today = LocalDate.now();
        LocalDate searchDate = today.plusDays(Integer.parseInt(dateNum) - 1);
        //查询购物车
        QueryWrapper<CoursesOrdersDetails> detailModel = new QueryWrapper<>();
        detailModel.eq("is_effective", false);
        detailModel.eq("creator", member.getId());
        detailModel.in("lb", "dc", "dcwm");
        detailModel.gt("quantity", 0);
        detailModel.ge("last_changed", searchDate);
        detailModel.le("last_changed", LocalDateTime.of(searchDate, LocalTime.MAX));
        List<CoursesOrdersDetails> lsList = coursesOrdersDetailsService.queryList(detailModel);
        ArrayList<CoursesOrdersDetails> gwcList = new ArrayList<>();
        ArrayList<String> delList = new ArrayList<>();
        Courses courses = new Courses();
        MealTime mealTime = new MealTime();
        if (lsList != null && lsList.size() > 0) {
            for (CoursesOrdersDetails coursesOrdersDetails : lsList) {
                courses = coursesOrdersDetails.getCourse();
                //查看菜品是否售卖
                mealTime = mealTimeService.query()
                        .eq("code", courses.getMealTimeCode())
                        .eq("mealType", courses.getType())
                        .eq("school_id", member.getSchoolId()).one();
                if (!courses.getStartTime().toLocalDate().equals(searchDate)) {
                    continue;
                }
                coursesOrdersDetails.setTotalPrice(coursesOrdersDetails.getPrice() * coursesOrdersDetails.getQuantity());
                if (StringUtils.hasText(coursesOrdersDetails.getRemark())) {
                    coursesOrdersDetails.setCourseName(courses.getNameCh() + "(" + coursesOrdersDetails.getRemark() + ")");
                    coursesOrdersDetails.setCourseNameEn(courses.getNameEn() + "(" + coursesOrdersDetails.getRemark() + ")");
                } else {
                    coursesOrdersDetails.setCourseName(courses.getNameCh());
                    coursesOrdersDetails.setCourseNameEn(courses.getNameEn());
                }
                for (Courses course : list) {
                    if (course.getId().equals(coursesOrdersDetails.getCourseId())) {
                        course.setNum(course.getNum() + coursesOrdersDetails.getQuantity().intValue());
                        break;
                    }
                }
                gwcList.add(coursesOrdersDetails);
            }
        }
        for (CourseType courseType : courseTypes) {
            courseType.setDCList(list.stream().filter(i -> i.getCoursesTypeId().equals(courseType.getId())).collect(Collectors.toList()));
        }
        if ("1".equals(schoolBaseInfo.getHasNut())) {
            model.addAttribute("nutrient", getNutrient(gwcList, member));
        }
        model.addAttribute("orderDeatailList", gwcList);
        model.addAttribute("courseTypes", courseTypes.stream().filter(i -> i.getDCList().size() > 0).collect(Collectors.toList()));
        return JSONObject.toJSONString(model);
    }

    /**
     * 今日菜单查询菜品
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/manage2", method = RequestMethod.POST)
    @ResponseBody
    public String indexCourse(Model model, HttpServletRequest request, HttpServletResponse response) {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
//        if (member.getRestaurant() == null) {
//            //设置第一个可用餐厅为默认餐厅
//            QueryWrapper<Restaurant> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("is_stop", false);
//            queryWrapper.eq("school_id", member.getSchoolId());
//            member.setRestaurant(restaurantService.list(queryWrapper).get(0));
//        }
        WebUtils.setSessionAttribute(request, SessionNames.LOGIN_USER, member);
        String typeId = request.getParameter("TypeId");
        String menuTimeCode = request.getParameter("MenuTimeCode");
        QueryWrapper<Courses> coursesQueryWrapper = new QueryWrapper<>();
        String schoolId = member.getSchoolId();
        coursesQueryWrapper.eq("school_id", schoolId).in("type", "dc", "wm", "dcwm").eq("meal_time_code", menuTimeCode);
        coursesQueryWrapper.eq("is_stop", "0").eq("is_delete", false)/*.eq("restaurant_id",member.getRestaurant().getId())*/;
        coursesQueryWrapper.ge("startTime", LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
        coursesQueryWrapper.le("endTime", LocalDateTime.of(LocalDate.now(), LocalTime.MAX).minusMinutes(1));
        List<Courses> coursesList = coursesService.list(coursesQueryWrapper);
        //查询菜品分类
        List<CourseType> courseTypes = coursesTypeService.coursesTypelist(member);
        for (Courses cc : coursesList) {
            //--------查询菜品主图开始----------
            List<CoursesImg> coursesImgList = coursesImgService.query()
                    .eq("course_pos_no", cc.getPosNo())
                    .isNotNull("img_path")
                    .isNotNull("img_url")
                    .orderByDesc("mainImg").list();
            cc.setCoursesImgList(coursesImgList);
            if (coursesImgList != null && coursesImgList.size() > 0) {
                cc.setImageMainPath(coursesImgList.get(0).getImgUrl());
            }
            //--------查询菜品主图结束----------
        }
        for (CourseType courseType : courseTypes) {
            courseType.setDCList(coursesList.stream().filter(i -> i.getCoursesTypeId().equals(courseType.getId())).collect(Collectors.toList()));
        }
        model.addAttribute("courseTypes", courseTypes.stream().filter(i -> i.getDCList().size() > 0).collect(Collectors.toList()));
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter("dCList", "mealTimeCode", "name", "nameEn", "courseTypes", "restaurantId", "courseId", "imageMainPath", "nameCh", "id", "remainCount", "price", "PosUnit", "num", "cnList");
        return JSONObject.toJSONString(model, filter);
    }


    /**
     * 模糊查询菜品
     *
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/getCoursesByName", method = RequestMethod.GET)
    @ResponseBody
    public String getCoursesBYname(Model model, HttpServletRequest request, HttpServletResponse response) {
        MemberBaseInfo memberInfo = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        String name = request.getParameter("name").trim();
        List<Courses> list = new ArrayList<>();
        QueryWrapper<Courses> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", false);
        queryWrapper.in("type", "wm", "dcwm");
//        queryWrapper.eq("restaurant_id", memberInfo.getRestaurant().getId());
        queryWrapper.eq("school_id", memberInfo.getSchoolId());
        queryWrapper.ge("startTime", LocalDate.now());
//        queryWrapper.lt("endTime", LocalDate.now().plusDays(1));
        queryWrapper.and(i -> i.like("name_ch", name).or().like("name_en", name));
        queryWrapper.orderByDesc("last_changed");
        list = coursesService.list(queryWrapper);
        //查询购物车
        QueryWrapper<CoursesOrdersDetails> detailModel = new QueryWrapper<>();
        detailModel.eq("is_effective", false);
        detailModel.eq("creator", memberInfo.getId());
        queryWrapper.in("type", "wm", "dcwm");
        detailModel.ge("last_changed", LocalDate.now());
        List<CoursesOrdersDetails> ordersDetailsList = coursesOrdersDetailsService.queryList(detailModel);
        for (Courses cc : list) {
            //--------查询菜品主图开始----------
            List<CoursesImg> coursesImgList = coursesImgService.query()
                    .eq("course_pos_no", cc.getPosNo())
                    .isNotNull("img_path")
                    .isNotNull("img_url")
                    .orderByDesc("mainImg").list();
            if (coursesImgList != null && coursesImgList.size() > 0) {
                cc.setImageMainPath(coursesImgList.get(0).getImgUrl());
            }
            //--------查询菜品主图结束----------
            for (CoursesOrdersDetails orderDetails : ordersDetailsList) {
                if (orderDetails.getCourseId().equals(cc.getId())) {
                    cc.setNum(orderDetails.getQuantity().intValue());
                    continue;
                }
            }
        }
        return JSONObject.toJSONString(list);
    }

    //获取营养信息
    private Map<String, Double> getNutrient(List<CoursesOrdersDetails> detailList, MemberBaseInfo member) {
        Map<String, Double> map = new HashMap<>();
        List<CourseNutrition> courseNutrition = new ArrayList<>();
        for (CoursesOrdersDetails coursesOrdersDetails : detailList) {
            courseNutrition = coursesNutritionService.query()
                    .eq("recipes_code", coursesOrdersDetails.getCourse().getPosNo())
                    .eq("is_delete", false).list();
            for (CourseNutrition courseNutrition2 : courseNutrition) {
                if (map.containsKey(courseNutrition2.getNutritionCode())) {
                    Double temVal = map.get(courseNutrition2.getNutritionCode());
                    temVal += courseNutrition2.getQuantity() * coursesOrdersDetails.getQuantity();
                    map.put(courseNutrition2.getNutritionCode(), temVal);
                } else {
                    Double val = courseNutrition2.getQuantity() * coursesOrdersDetails.getQuantity();
                    map.put(courseNutrition2.getNutritionCode(), val);
                }
            }
        }
        HashMap<String, Double> hashMap = new HashMap<>();
        if (Finals.ZhOrEn.Z.equals(member.getZhOrEn())) {
            for (String key : map.keySet()) {
                if (Finals.NUT_CODE_NL.equals(key)) {
                    hashMap.put("能量(kcal)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_TSHHW.equals(key)) {
                    hashMap.put("碳水化物(g)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_SSXW.equals(key)) {
                    hashMap.put("钠(mg)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_DBZ.equals(key)) {
                    hashMap.put("蛋白质(g)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_ZF.equals(key)) {
                    hashMap.put("脂肪(g)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
            }
        } else {
            for (String key : map.keySet()) {
                if (Finals.NUT_CODE_NL.equals(key)) {
                    hashMap.put("Energy(kcal)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_TSHHW.equals(key)) {
                    hashMap.put("Carbohydrate(g)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_SSXW.equals(key)) {
                    hashMap.put("Na(mg)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_DBZ.equals(key)) {
                    hashMap.put("Protein(g)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_ZF.equals(key)) {
                    hashMap.put("Fat(g)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
            }
        }
        return hashMap;
    }


    /**
     * 查询菜品规格标签
     *
     * @param id
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/getCoursesNote", method = RequestMethod.POST)
    @ResponseBody
    public String getCoursesNote(@RequestParam String courseTypeId, Model model, HttpServletRequest request, HttpServletResponse response) {

        //单选规格
        List<CourseNotes> danXuanList = courseNotesService.listDanXuan(courseTypeId);
        //多选规格
        List<CourseNotes> duoXuanList = courseNotesService.listDuoXuan(courseTypeId);
        model.addAttribute("danxuan", danXuanList.size() > 0 ? danXuanList : null);
        model.addAttribute("duoxuan", duoXuanList.size() > 0 ? duoXuanList : null);
        if (duoXuanList.size() <= 0 && danXuanList.size() <= 0) {
            model.addAttribute("result", false);
        } else {
            model.addAttribute("result", true);
        }
        return JSONObject.toJSONString(model);
    }

    /**
     * 菜品详情
     *
     * @param id
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/getCoudetail", method = RequestMethod.POST)
    @ResponseBody
    public String getCoudetail(@RequestParam("id") String id, Model model, HttpServletRequest request) {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);

        DecimalFormat df = new DecimalFormat("######0.00");
        Courses courses = coursesService.findById(id);

        //--------查询菜品主图开始----------
        QueryWrapper<CoursesImg> coursesImgModel = new QueryWrapper<>();
        coursesImgModel.eq("course_pos_no", courses.getPosNo());
        coursesImgModel.isNotNull("img_path");
        coursesImgModel.isNotNull("img_url");
        coursesImgModel.orderByAsc("sort");
        List<CoursesImg> coursesImgList = coursesImgService.list(coursesImgModel);
        if (coursesImgList != null && coursesImgList.size() > 1) {
            courses.setImageMainPath(coursesImgList.get(1).getImgUrl());
        }
        //菜品介绍图
        if (coursesImgList != null && coursesImgList.size() > 2) {
            courses.setDescriptionImg(coursesImgList.get(2).getImgUrl());
        }
        //--------查询菜品主图结束----------
        //查询菜品是否在售
        QueryWrapper<MealTime> mealTimeModels = new QueryWrapper<>();
        mealTimeModels.eq("mealType", courses.getType());
        mealTimeModels.eq("school_id", member.getSchoolId());
        mealTimeModels.eq("code", courses.getMealTimeCode());
        MealTime mealTime = mealTimeService.getOne(mealTimeModels, false);
        LocalDateTime nowTime = LocalDateTime.now();


        //是否今日菜品
        if (nowTime.toLocalDate().isBefore(courses.getStartTime().toLocalDate())) {
            courses.setTodayCourse(false);
            courses.setSell(true);
        } else if (nowTime.toLocalDate().isEqual(courses.getStartTime().toLocalDate())) {
            courses.setTodayCourse(true);
            //是否在售
            if (nowTime.toLocalTime().isAfter(mealTime.getDCendTime().toLocalTime())) {
                courses.setSell(false);
            } else {
                courses.setSell(true);
            }
        }
        if (courses.getRemainCount() <= 0 || "1".equals(courses.getIsStop())) {
            courses.setSell(false);
        }
        List<CourseNutrition> list = new ArrayList<CourseNutrition>();
        if (null != courses.getCnList() && courses.getCnList().size() > 0) {
            for (CourseNutrition courseNutrition : courses.getCnList()) {
                courseNutrition.setQuantity(Double.valueOf(df.format(courseNutrition.getQuantity())));
                list.add(courseNutrition);
                //营养标签
                if ("dz.png".equals(courseNutrition.getTagLogo())) {
                    courses.setDzLogo("dz.png");
                } else if ("dk.png".equals(courseNutrition.getTagLogo())) {
                    courses.setDkLogo("dk.png");
                } else if ("dy.png".equals(courseNutrition.getTagLogo())) {
                    courses.setDyLogo("dy.png");
                } else if ("gw.png".equals(courseNutrition.getTagLogo())) {
                    courses.setGwLogo("gw.png");
                }
            }
        }
        model.addAttribute("courseNutritionlist", courses.getCnList());
        model.addAttribute("courses", courses);
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(CourseNutrition.class, "nutritionName", "quantity", "nutritionMeasurement");
        return JSONObject.toJSONString(model, filter);
    }


    /**
     * 浏览器跳转菜品详情
     *
     * @param id
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/getCoudetail2", method = RequestMethod.POST)
    @ResponseBody
    public String getCoudetail2(@RequestParam("id") String id, Model model, HttpServletRequest request) {
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter("portionsize", "descriptionImg", "nutritionName", "quantity", "nutritionMeasurement", "courses", "courseNutritionlist", "description", "dkLogo", "dyLogo", "dzLogo", "gwLogo", "nameCh", "nameEn", "imageMainPath", "price");
        DecimalFormat df = new DecimalFormat("######0.00");
        Courses courses = coursesService.findById(id);
        //--------查询菜品主图开始----------
        QueryWrapper<CoursesImg> coursesImgModel = new QueryWrapper<>();
        coursesImgModel.eq("course_pos_no", courses.getPosNo());
        coursesImgModel.isNotNull("img_path");
        coursesImgModel.isNotNull("img_url");
        coursesImgModel.orderByAsc("sort");
        List<CoursesImg> coursesImgList = coursesImgService.list(coursesImgModel);
        if (coursesImgList != null && coursesImgList.size() > 1) {
            courses.setImageMainPath(coursesImgList.get(1).getImgUrl());
        }
        //菜品介绍图
        if (coursesImgList != null && coursesImgList.size() > 2) {
            courses.setDescriptionImg(coursesImgList.get(2).getImgUrl());
        }
        //--------查询菜品主图结束----------
        List<CourseNutrition> courseNutritionlist = courses.getCnList();
        List<CourseNutrition> list = new ArrayList<CourseNutrition>();
        if (null != courseNutritionlist && courseNutritionlist.size() > 0) {
            for (CourseNutrition courseNutrition : courseNutritionlist) {
                courseNutrition.setQuantity(Double.valueOf(df.format(courseNutrition.getQuantity())));
                list.add(courseNutrition);
                //营养标签
                if ("dz.png".equals(courseNutrition.getTagLogo())) {
                    courses.setDzLogo("dz.png");
                } else if ("dk.png".equals(courseNutrition.getTagLogo())) {
                    courses.setDkLogo("dk.png");
                } else if ("dy.png".equals(courseNutrition.getTagLogo())) {
                    courses.setDyLogo("dy.png");
                } else if ("gw.png".equals(courseNutrition.getTagLogo())) {
                    courses.setGwLogo("gw.png");
                }
            }
        }
//        model.addAttribute("imgList", coursesImgList);
        model.addAttribute("courseNutritionlist", list);
        model.addAttribute("courses", courses);
        return JSONObject.toJSONString(model, filter, SerializerFeature.DisableCircularReferenceDetect);
    }

    @GetMapping("updateCourseImg")
    @ResponseBody
    public void updateCourseImg() {
        System.out.println("开始同步图片");
        //获取本周今日后所有菜品编号
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        String accessKeyId = "LTAI4G6hfiVamzyUnkxmmw6p";
        String accessKeySecret = "olnhSV9098scnsmcpfMLt5rkpZB688";
        String bucketName = "opxprod";
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 设置URL过期时间
        Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000 * 24 * 360L);
        List<Courses> coursesList = coursesService.query().select("DISTINCT pos_no").ge("startTime", LocalDate.now()).list();
        log.info("需更新图片菜品数量:{}", coursesList.size());
        List<CoursesImg> coursesImgList;
        for (Courses courses : coursesList) {
            //查询图片
            log.info("更新菜品图片,posNo:{}", courses.getPosNo());
            coursesImgList = coursesImgService.query()
                    .eq("course_pos_no", courses.getPosNo())
                    .isNotNull("img_path")
                    .ne("img_path", "").list();
            for (CoursesImg coursesImg : coursesImgList) {
                // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
                coursesImg.setImgUrl(ossClient.generatePresignedUrl(bucketName, coursesImg.getImgPath(), expiration).toString());
                coursesImg.setLastChangedTime(LocalDateTime.now());
            }
            coursesImgService.updateBatchById(coursesImgList);
        }
//         关闭OSSClient。
        ossClient.shutdown();
        System.out.println("同步结束");
    }


    /**
     * 向请求方发送json字符串
     *
     * @param response
     * @throws IOException
     */
    protected void writeJson(HttpServletResponse response, Object obj) throws IOException {
        response.setHeader("ContentType", "text/json");
        response.setHeader("Content-Type", "text/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.print(obj);
        out.close();
    }
}
